package com.tronsis.distribution.activity.me.stock;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.me.address.AddressManageActivity;
import com.tronsis.distribution.bean.AddressBean;
import com.tronsis.distribution.bean.MyStockBean;
import com.tronsis.distribution.biz.factory.OrderBizFactory;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.IntentUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class StockDeliverConfirmActivity extends ToolBarBaseActivity {

    @BindView(R.id.rv_goods)
    RecyclerView mRvGoods;
    @BindView(R.id.tv_more)
    TextView mTvMore;
    @BindView(R.id.tv_amount)
    TextView mTvAmount;
    @BindView(R.id.ll_add_address)
    LinearLayout mLlAddAddress;
    @BindView(R.id.ll_address_info)
    LinearLayout mLlAddressInfo;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_phone)
    TextView mTvPhone;
    @BindView(R.id.tv_address)
    TextView mTvAddress;

    private String mAddressId;
    private double mPrice;

    private CommonAdapter<MyStockBean> mAdapter;
    private List<MyStockBean> mGoodsList = new ArrayList<>();
    private List<MyStockBean> mGoodsAllList = new ArrayList<>();
    private List<MyStockBean> mGoodsPartList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_deliver_confirm);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.delivery), getString(R.string.confirm));

        mGoodsAllList = (ArrayList<MyStockBean>) getIntent().getSerializableExtra("MyStockList");
        if (mGoodsAllList == null) {
            mGoodsAllList = new ArrayList<>();
        }
        initRv();
        initData();
//      httpGetPrice();
    }

    private void initRv() {
        mAdapter = new CommonAdapter<MyStockBean>(mContext, mGoodsList, R.layout.item_stock_deliver) {
            @Override
            protected void convert(final ViewHolder holder, final MyStockBean stockBean, int position) {
                holder.setImageByUrl(mContext, R.id.iv_cover, Url.FILE_DOWNLOAD + stockBean.getCoverFid());
                holder.setText(R.id.tv_product_name, stockBean.getName());
                holder.setText(R.id.tv_amount, "x" + stockBean.getCount());

                holder.setOnClickListener(R.id.btn_note, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        holder.setVisible(R.id.ll_note, true);
                        stockBean.setNote(true);
                    }
                });

                if (stockBean.isNote()) {
                    holder.setVisible(R.id.ll_note, true);
                } else {
                    holder.setVisible(R.id.ll_note, false);
                }

                final EditText editText = holder.getView(R.id.et_remark);
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        String string = editText.getText().toString();
                        if (!TextUtils.isEmpty(string)) {
                            stockBean.setRemarks(string);
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });
            }
        };


        int height = DisplayUtil.getInstance(mContext).dp2px(1);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRvGoods.addItemDecoration(decoration);
        mRvGoods.setLayoutManager(new LinearLayoutManager(mContext));
        mRvGoods.setHasFixedSize(true);
        mRvGoods.setNestedScrollingEnabled(false);
        mRvGoods.setAdapter(mAdapter);
    }

    private void initData() {
        mGoodsList.clear();
        if (mGoodsAllList.size() > 6) {
            mTvMore.setVisibility(View.VISIBLE);
            for (int i = 0; i < 6; i++) {
                mGoodsPartList.add(mGoodsAllList.get(i));
            }
            mGoodsList.addAll(mGoodsPartList);
        } else {
            mGoodsList.addAll(mGoodsAllList);
        }
        mAdapter.notifyDataSetChanged();

        double freight = 0;
        for (MyStockBean stockBean : mGoodsAllList) {
            freight = freight + stockBean.getFreight() * stockBean.getCount();
        }
        mTvAmount.setText(getString(R.string.format_rmb, freight));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            AddressBean addressBean = (AddressBean) data.getSerializableExtra("AddressBean");
            if (addressBean != null) {
                mLlAddressInfo.setVisibility(View.VISIBLE);
                mTvName.setText(getString(R.string.format_deliver_name, addressBean.getName()));
                mTvPhone.setText(addressBean.getPhone());
                mTvAddress.setText(CommonUtil.getRegionString(addressBean.getRegion()) + addressBean.getDetail());
                mAddressId = addressBean.getId();
            }
        }
    }

    @Override
    protected void onToolbarClicked(int paramId) {
        super.onToolbarClicked(paramId);
        switch (paramId) {
            case RIGHT_TEXT:
                if (TextUtils.isEmpty(mAddressId)) {
                    ToastUtil.showMessage(mContext, "请选择收货信息");
                    return;
                }
                httpSubmit(mAddressId);
                break;
        }
    }

    @OnClick(R.id.tv_more)
    void onMoreClick() {
        if (mGoodsList.size() > 6) {
            mGoodsList.clear();
            mGoodsList.addAll(mGoodsPartList);
            mTvMore.setText("查看全部");
        } else {
            mGoodsList.clear();
            mGoodsList.addAll(mGoodsAllList);
            mTvMore.setText("收起");
        }
        mAdapter.notifyDataSetChanged();
    }


    @OnClick(R.id.ll_add_address)
    void addAddressClick() {
        Intent intent = new Intent(mContext, AddressManageActivity.class);
        intent.setType("select");
        startActivityForResult(intent, 0x176);
    }

    private void httpGetPrice() {
        try {
            OrderBizFactory.createBiz().getStockTotalPrice(this, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    Double d = (Double) data;
                    if (d != null) {
                        mPrice = d;
                        mTvAmount.setText(getString(R.string.format_rmb, mPrice));
                    }
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void httpSubmit(String addrId) {
        List<RequestBody> list = new ArrayList<>();
        for (MyStockBean myStockBean : mGoodsAllList) {
            RequestBody body = new RequestBody(myStockBean.getProductId(), myStockBean.getRemarks(), myStockBean.getCount());
            list.add(body);
        }
        try {
            OrderBizFactory.createBiz().applyDelivery(this, addrId, list, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    IntentUtil.goBackToActivityRefresh(StockDeliverConfirmActivity.this, StockActivity.class);
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private static class RequestBody {
        private int amount;
        private String productId;
        private String remarks;

        public RequestBody(String productId, String remarks, int amount) {
            this.amount = amount;
            this.productId = productId;
            this.remarks = remarks;
        }

    }


}
